<template>
  <div>
    <h1>营养知识</h1>
    <el-form :inline="true">
      <el-form-item label="">
        <el-input v-model="searchForm.food" placeholder="食物关键词">
        </el-input>
      </el-form-item>

      <el-select v-model="searchForm.type">
        <el-option label="请选择..." value=""></el-option>
        <el-option
          v-for="item in typeList"
          :key="item.id"
          :label="item.value"
          :value="item.id"
        >
        </el-option>
      </el-select>
      <el-button class="search" type="success" @click="getKnowledge()"
        >查询</el-button
      >
      <el-button type="primary" @click="addForm = true" v-if="hasAuth('know:add')">新增营养知识</el-button>
      <el-button type="" v-if="hasAuth('knowledge:upload')"  @click="download">下载营养知识上传文件模板</el-button>
      <download-excel
              class="export-excel-wrapper"
              :data="allList"
              :fields="fields"
              :name="title"
            >
              <!-- 上面可以自定义自己的样式，还可以引用其他组件button -->
              <el-button type="success" size="mini">导出所有营养知识</el-button>
       </download-excel>
      <el-upload
        :action="action"
        :file-list="modeList"
        :http-request="modeUpload"
        class="update"
        v-if="hasAuth('knowledge:upload')"
      >
        <el-button  type="primary">上传营养文件上传</el-button>
      </el-upload>
      <el-button @click="upload" v-if="hasAuth('knowledge:upload')" >保存上传数据</el-button>
      
    </el-form>

    <el-table
      ref="multipleTable"
      :data="knowledgeList"
      tooltip-effect="dark"
      style="width: 100%"
    >
      <el-table-column label="食物搭配" prop="food" width="150">
      </el-table-column>
      <el-table-column label="类型" prop="type" width="100"> </el-table-column>
      <el-table-column label="效果" prop="description" width="200">
      </el-table-column>
      <el-table-column label="原因" prop="result" >
      </el-table-column>
      <el-table-column label="操作" v-if="hasAuth('know:edit')">
        <template slot-scope="scope">
          <el-button type="text" @click="editHandle(scope.row.id)">编辑</el-button>
          <el-divider direction="vertical"></el-divider>

          <template>
            <el-popconfirm
              title="这是一段内容确定删除吗？"
              @confirm="delHandle(scope.row.id)"
            >
              <el-button type="text" slot="reference">删除</el-button>
            </el-popconfirm>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      title="增加页面"
      :visible.sync="addForm"
      width="600px"
      :before-close="handleClose"
    >
      <el-form
        :model="knownledge"
        :rules="formRules"
        ref="knownledge"
        label-width="100px"
        class="demo-editForm"
      >
        <el-form-item label="食物搭配分类" prop="type" label-width="150px">
          <el-select v-model="knownledge.type">
            <el-option label="请选择..." value=""></el-option>
            <el-option
              v-for="item in typeList"
              :key="item.id"
              :label="item.value"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="食物" prop="food" label-width="150px">
          <el-input v-model="knownledge.food" placeholder=""></el-input>
        </el-form-item>

        <el-form-item label="产生效果" prop="description" label-width="150px">
          <el-input v-model="knownledge.description" placeholder=""></el-input>
        </el-form-item>

        <el-form-item label="产生原因" prop="result" label-width="150px">
          <el-input v-model="knownledge.result" placeholder=""></el-input>
        </el-form-item>

        <el-form-item class="add">
          <el-button
            v-if="knownledge.id == undefined"
            type="primary"
            @click="submitForm('knownledge')"
            >创建</el-button
          >
          <el-button v-else type="primary" @click="submitForm('knownledge')"
            >更新</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[10, 20, 50, 100]"
      :current-page="current"
      :page-size="size"
      :total="total"
    >
    </el-pagination>
  </div>
</template>

<script>
import { mapState } from "vuex";

export default {
  name: "Knowledge",
  data() {
    return {
      total: 0,
      size: 10,
      current: 1,
      knowledgeList: [],
      title:"营养知识点.xls",
      fields:{
          "食物搭配":"food",
          "类型":"type",
          "效果":"description",
          "原因":"result"
      },
      addForm: false,
      searchForm: {
        food: "",
        type: "",
      },
      action: "https://jsonplaceholder.typicode.com/posts/",
      mode: {},
      modeList: [],
      typeList: [],
      knownledge: {},
      allList: [],
      formRules: {
        type: [
          {
            required: true,
            message: "请选择食物搭配分类",
            trigger: ["blur", "change"],
          },
        ],
        food: [{ required: true, message: "请输入食物", trigger: "blur" }],
        description: [
          { required: true, message: "请输入产生效果", trigger: "blur" },
        ],
        result: [
          { required: true, message: "请输入产生原因", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    modeUpload: function (item) {
      console.log(item.file);
      this.mode = item.file;
    },
    upload: function() {
      let fd = new FormData()
      fd.append('file', this.mode)
      this.$axios.post('/health/knowledge/load', fd, {
         headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(res => {
         this.$message.success(res.data.data);
         this.searchForm = {}
         this.getKnowledge()
      })
    },
    handleClose() {
      this.resetForm();
    },
    resetForm() {
      this.addForm = false;
      this.knownledge = {};
    },
    getKnowledge() {
      this.$axios
        .get("/health/knowledge/value/list", {
          params: {
            food: this.searchForm.food,
            type: this.searchForm.type,
            current: this.current,
            size: this.size,
          },
        })
        .then((res) => {
          this.knowledgeList = res.data.data.records;
          this.size = res.data.data.size;
          this.current = res.data.data.current;
          this.total = res.data.data.total;
        });
        this.getAll();
    },
    getDict() {
      this.$axios.get("/sys/dict/value/list/knowledgeType").then((res) => {
        this.typeList = res.data.data;
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$axios
            .post(
              "/health/knowledge/" + (this.knownledge.id ? "update" : "save"),
              this.knownledge
            )
            .then((res) => {
              this.$message({
                showClose: true,
                message: res.data.data,
                type: "success",
                onClose: () => {
                  this.getKnowledge();
                  this.resetForm();
                },
              });
            });
          this.addForm = false;
        }
      });
    },
    editHandle(id) {
      this.$axios.get("/health/knowledge/info/" + id).then((res) => {
        this.knownledge = res.data.data;
        this.addForm = true;
      });
    },
    delHandle(id) {
      this.$axios.get("/health/knowledge/delete?id=" + id).then((res) => {
        this.$message({
          showClose: true,
          message: res.data.data,
          type: "success",
          onClose: () => {
            this.getKnowledge();
          },
        });
      });
    },
    handleSizeChange(val) {
      this.size = val;
      this.getKnowledge();
    },
    handleCurrentChange(val) {
      this.current = val;
      this.getKnowledge();
    },
    getAll(){
      this.$axios.get('/health/knowledge/allList').then((res)=>{
        this.allList = res.data.data
      })
    },
    download(){
      window.location.href =  this.$axios.defaults.baseURL + "/health/knowledge/download";
    }
  },
  created() {
    this.getKnowledge();
    this.getDict();
  },
};
</script>

<style scoped>
.update {
  display: inline-block;
  margin-left: 10px;
  margin-right: 10px;
}
.export-excel-wrapper{
  display: inline;
  margin-left: 1%;
}
.el-table {
  font-size: 18px;
}
</style>